<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="formData.dataType" placeholder="请选择数据类型" style="width: 100%">
                <el-option v-for="dict in getDictDatas(DICT_TYPE.M_PLAN_TYPE)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划编号" prop="planTaskNo">
              <el-input v-model="formData.planTaskNo" placeholder="请输入计划编号" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划任务类型" prop="planTaskType">
              <el-select v-model="formData.planTaskType" placeholder="请选择计划任务类型" style="width: 100%">
                <el-option label="设备" value="1" />
                <el-option label="工装" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" placeholder="请输入计划名称" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划开始时间" prop="planStartDateTime">
              <el-date-picker clearable v-model="formData.planStartDateTime" type="date" value-format="timestamp"
                placeholder="选择计划开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划结束时间" prop="planEndDateTime">
              <el-date-picker clearable v-model="formData.planEndDateTime" type="date" value-format="timestamp"
                placeholder="选择计划结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="实际开始时间" prop="actualStartDateTime">
              <el-date-picker clearable v-model="formData.actualStartDateTime" type="date" value-format="timestamp"
                placeholder="选择实际开始时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="实际结束时间" prop="actualEndDateTime">
              <el-date-picker clearable v-model="formData.actualEndDateTime" type="date" value-format="timestamp"
                placeholder="选择实际结束时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="计划执行人" prop="planExecutorUserId">
              <el-select v-model="formData.planExecutorUserId" placeholder="请选择计划执行人" filterable style="width: 100%"
                remote :remote-method="planRemoteMethod" :loading="planUserLoading" @change="handlePlanExecutorChange">
                <el-option v-for="user in planUserList" :key="user.id" :label="user.nickname" :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="实际执行人" prop="actualExecutorUserId">
              <el-select v-model="formData.actualExecutorUserId" placeholder="请选择实际执行人" filterable style="width: 100%"
                remote :remote-method="actualRemoteMethod" :loading="actualUserLoading"
                @change="handleActualExecutorChange">
                <el-option v-for="user in actualUserList" :key="user.id" :label="user.nickname"
                  :value="user.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="设备巡检计划" prop="maintenancePlanItemId">
              <el-select v-model="formData.maintenancePlanItemId" placeholder="请输入计划名称进行搜索" filterable style="width: 100%" remote
                :remote-method="planNameRemoteMethod" :loading="planLoading" @change="handlePlanChange">
                <el-option v-for="plan in planList" :key="plan.id" :label="plan.planName" :value="plan.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptList" :normalizer="normalizer"  @select="deptChange"  placeholder="选择所属部门" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="设备" prop="devicesId">
              <el-select v-model="formData.devicesId" placeholder="请输入设备名称进行搜索" filterable style="width: 100%" remote
                :remote-method="deviceRemoteMethod" :loading="deviceLoading" @change="handleDeviceChange">
                <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName"
                  :value="device.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="所需时间(min)" prop="planUseTime">
              <el-input v-model="formData.planUseTime" placeholder="请输入所需时间(min)" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="dict.value"
                  :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="执行状态" prop="executeStatus">
              <el-select v-model="formData.executeStatus" placeholder="请选择执行状态" style="width: 100%">
                <el-option v-for="dict in getDictDatas(DICT_TYPE.EXECUTE_STATUS)" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">

            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="计划描述">
          <Editor v-model="formData.planDescription" :min-height="192" />
        </el-form-item>

        <el-form-item label="保养内容">
          <Editor v-model="formData.planContent" :min-height="192" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as MaintenancePlanTaskApi from '@/api/devices/maintenanceplantask';
import * as MaintenancePlanApi from '@/api/devices/maintenanceplan/index.js';
import * as UserApi from '@/api/system/user';
import * as DeviceApi from '@/api/system/device';
import { listDept } from "@/api/system/dept";
import Editor from '@/components/Editor';
import { getDictDataLabel, getDictDatas, DICT_TYPE } from '@/utils/dict';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "MaintenancePlanTaskForm",
  components: {
    Editor,
    Treeselect
  },
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        dataType: undefined,
        planTaskNo: undefined,
        planTaskType: undefined,
        planName: undefined,
        planDescription: undefined,
        planStartDateTime: undefined,
        planEndDateTime: undefined,
        actualStartDateTime: undefined,
        actualEndDateTime: undefined,
        planExecutorUserId: undefined,
        planExecutorUserName: undefined,
        actualExecutorUserId: undefined,
        actualExecutorUserName: undefined,
        maintenancePlanItemId: undefined,
        planContent: undefined,
        deptId: undefined,
        deptName: undefined,
        devicesId: undefined,
        devicesName: undefined,
        planUseTime: undefined,
        status: 1, // 默认开启
        executeStatus: undefined,
        remark: undefined,
      },
      // 计划执行人列表
      planUserList: [],
      // 计划执行人加载状态
      planUserLoading: false,
      // 实际执行人列表
      actualUserList: [],
      // 实际执行人加载状态
      actualUserLoading: false,
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 部门列表
      deptList: [],
      // 计划列表
      planList: [],
      // 计划加载状态
      planLoading: false,
      // 表单校验
      formRules: {
        planStartDateTime: [{ required: true, message: '计划开始时间不能为空', trigger: 'blur' }],
        planEndDateTime: [{ required: true, message: '计划结束时间不能为空', trigger: 'blur' }],
        actualStartDateTime: [{ required: true, message: '实际开始时间不能为空', trigger: 'blur' }],
        actualEndDateTime: [{ required: true, message: '实际结束时间不能为空', trigger: 'blur' }],
        planExecutorUserId: [{ required: true, message: '计划执行人id不能为空', trigger: 'blur' }],
        actualExecutorUserId: [{ required: true, message: '实际执行人id不能为空', trigger: 'blur' }],
        maintenancePlanItemId: [{ required: true, message: '设备/工装巡检计划-内容id不能为空', trigger: 'blur' }],
        planContent: [{ required: true, message: '保养内容不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '所属部门id不能为空', trigger: 'blur' }],
        devicesId: [{ required: true, message: '设备/工装id不能为空', trigger: 'blur' }],
        planUseTime: [{ required: true, message: '所需时间(分钟)不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态0-未完成1-已完成不能为空', trigger: 'blur' }],
        executeStatus: [{ required: true, message: '执行状态不能为空', trigger: 'blur' }],
      },
    };
  },
  methods: {
    deptChange(e){
      this.formData.deptName = e.name;
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children,
      };

      // 关键：如果不是第三级节点，则禁用
      if (node.deptType == 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    /** 获取部门列表 */
    async getDeptList() {
      try {
        const response = await listDept();
        this.deptList = this.handleTree(response.data, "id")[0].children;
      } catch (error) {
        console.error('获取部门列表失败', error);
      }
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 加载部门列表
      await this.getDeptList();
      // 修改时，设置数据
      if (id) {
        this.dialogTitle = "编辑设备点巡检/保养任务";
        this.formLoading = true;
        try {
          const res = await MaintenancePlanTaskApi.getMaintenancePlanTask(id);
          this.formData = res.data;
          // 如果有计划执行人ID，需要显示对应的用户名
          if (this.formData.planExecutorUserId) {
            await this.planRemoteMethod(this.formData.planExecutorUserName || '');
          }
          // 如果有实际执行人ID，需要显示对应的用户名
          if (this.formData.actualExecutorUserId) {
            await this.actualRemoteMethod(this.formData.actualExecutorUserName || '');
          }
          // 如果有设备ID，需要显示对应的设备名称
          if (this.formData.devicesId) {
            await this.deviceRemoteMethod(this.formData.devicesName || '');
          }
          // 如果有计划ID，需要显示对应的计划名称
          if (this.formData.maintenancePlanItemId) {
            await this.planRemoteMethod(this.formData.planName || '');
          }
        } finally {
          this.formLoading = false;
        }
      } else {
        await this.deviceRemoteMethod('')
        await this.actualRemoteMethod('')
        await this.planRemoteMethod('')
        await this.planNameRemoteMethod('')
        this.dialogTitle = "新增设备点巡检/保养任务";
      }
    },

    /** 计划执行人远程搜索方法 */
    async planRemoteMethod(query) {
      this.planUserLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          nickname: query // 根据用户名搜索
        };
        const response = await UserApi.listUser(params);
        this.planUserList = response.data.list;
      } catch (error) {
        console.error('搜索计划执行人失败', error);
        this.planUserList = [];
      } finally {
        this.planUserLoading = false;
      }
    },

    /** 实际执行人远程搜索方法 */
    async actualRemoteMethod(query) {
      this.actualUserLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          nickname: query // 根据用户名搜索
        };
        const response = await UserApi.listUser(params);
        this.actualUserList = response.data.list;
      } catch (error) {
        console.error('搜索实际执行人失败', error);
        this.actualUserList = [];
      } finally {
        this.actualUserLoading = false;
      }
    },

    /** 处理计划执行人选择 */
    handlePlanExecutorChange(userId) {
      const selectedUser = this.planUserList.find(user => user.id === userId);
      if (selectedUser) {
        this.formData.planExecutorUserName = selectedUser.username;
      } else {
        this.formData.planExecutorUserName = undefined;
      }
    },

    /** 处理实际执行人选择 */
    handleActualExecutorChange(userId) {
      const selectedUser = this.actualUserList.find(user => user.id === userId);
      if (selectedUser) {
        this.formData.actualExecutorUserName = selectedUser.username;
      } else {
        this.formData.actualExecutorUserName = undefined;
      }
    },

    /** 计划远程搜索方法 */
    async planNameRemoteMethod(query) {
      this.planLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          planName: query,
          cycleType:1
        };
        const response = await MaintenancePlanApi.getMaintenancePlanPage(params);
        this.planList = response.data.list;
      } catch (error) {
        console.error('搜索计划失败', error);
        this.planList = [];
      } finally {
        this.planLoading = false;
      }
    },

    /** 处理计划选择 */
    handlePlanChange(planId) {
      const selectedPlan = this.planList.find(plan => plan.id === planId);
      if (selectedPlan) {
        this.formData.planName = selectedPlan.planName;
      } else {
        this.formData.planName = undefined;
      }
    },

    /** 设备远程搜索方法 */
    async deviceRemoteMethod(query) {
      this.deviceLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('搜索设备失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    /** 处理设备选择 */
    handleDeviceChange(deviceId) {
      const selectedDevice = this.deviceList.find(device => device.id === deviceId);
      if (selectedDevice) {
        this.formData.devicesName = selectedDevice.deviceName;
      } else {
        this.formData.devicesName = undefined;
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await MaintenancePlanTaskApi.updateMaintenancePlanTask(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await MaintenancePlanTaskApi.createMaintenancePlanTask(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        dataType: undefined,
        planTaskNo: undefined,
        planTaskType: undefined,
        planName: undefined,
        planDescription: undefined,
        planStartDateTime: undefined,
        planEndDateTime: undefined,
        actualStartDateTime: undefined,
        actualEndDateTime: undefined,
        planExecutorUserId: undefined,
        planExecutorUserName: undefined,
        actualExecutorUserId: undefined,
        actualExecutorUserName: undefined,
        maintenancePlanItemId: undefined,
        planContent: undefined,
        deptId: undefined,
        deptName: undefined,
        devicesId: undefined,
        devicesName: undefined,
        planUseTime: undefined,
        status: 1, // 默认开启
        executeStatus: undefined,
        remark: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>
